package main

import (
	"fmt"
	"net"
	"sort"
)

func main() {
	ports := make(chan int, 100)
	result := make(chan int)
	var closePort []int
	var openPort []int
	address := "223.111.179.27"
	for i := 1; i < cap(ports); i++ {
		//	wg.Add(1)
		//	address := fmt.Sprintf("180.101.49.12:%d", i)
		//	go func(j int) {
		//
		//		//go dail(address)
		//		defer wg.Done()
		//		conn, err := net.Dial("tcp", address)
		//		if err != nil {
		//			fmt.Printf("%s 关闭了\n", address)
		//			return
		//		}
		//		conn.Close()
		//		fmt.Printf("%s 打开了！！！\n", address)
		//	}(i)
		//}
		go worker(ports, address, result) //生成100个go程
	}
	go func() {
		for i := 1; i < 21; i++ {
			ports <- i
		}
	}()

	for i := 1; i < 21; i++ {
		port := <-result
		if port != 0 {
			openPort = append(openPort, port)
		} else {
			closePort = append(closePort, port)
		}
	}

	close(ports)
	close(result)
	sort.Ints(openPort)
	for _, i := range openPort {
		fmt.Printf("%s:%d 打开了\n", address, i)
	}
	sort.Ints(closePort)
	for _, i := range closePort {
		fmt.Printf("%s:%d 关闭了\n", address, i)
	}
}

//func dail(add string) {
//	defer wg.Done()
//	conn, err := net.Dial("tcp", add)
//	if err != nil {
//		fmt.Printf("%s 关闭了\n", add)
//		return
//	}
//	conn.Close()
//	fmt.Printf("%s 打开了！！！\n", add)
//}
func worker(ports chan int, address string, result chan int) {
	for p := range ports {
		//fmt.Println(p)
		add := fmt.Sprintf("%s:%d", address, p)
		conn, err := net.Dial("tcp", add)
		if err != nil {
			result <- 0
			continue
		}
		conn.Close()
		result <- p
		//fmt.Printf("%s 打开了！！！\n", add)
	}

}
